#include "geminai_hlw8032.h"

#define HLW8032_UART_PORT   BK_UART_2
/*创建任务需要2K*/


void hlw8032_init(void)
{
	//串口初始化
	//user_uart_rtos_init();
	//添加一个定时任务
    //AddTask_TmrQueue(1*60*60*1000, 1*60*60*1000, powerConTimingReport);
}

//==============================================================================

//crc校验
bool Check_CRC(uint8_t *pdat,int length)
{
	unsigned int Check_Sum = 0,i;
	unsigned char CRC_Data =0;
	
	for(i = 0; i < length; i++)
	{
		Check_Sum +=*pdat++;
	}
	Check_Sum = (unsigned char)Check_Sum;
	CRC_Data = (*pdat++);
	if(CRC_Data == (unsigned char)Check_Sum)
	{
		return 1;
	}
	return 0;
}

//接收电量计中传输的数据（length 要等于24）
void receive_uart_handle(uint8_t *p_data,int length)
{
	static uint8_t old_data[24] = {0};
	// static uint8_t printf_cnt = 0;
	
	if((24 == length) && (0x5A == p_data[1]) && (Check_CRC(&p_data[2],length-3)))
	{
		// printf("******************receive_uart_handle*************\n");
		// printf("******************receive_uart_handle*************\n");
		// printf("******************receive_uart_handle*************\n");
		if(memcmp(p_data,old_data,sizeof(old_data)))
		{
			memcpy(old_data,p_data,sizeof(old_data));
			DealUartInf(p_data,length);

			//接收20次打印一次
			// if(printf_cnt++ > 20)
			if(0)
			{
				// printf_cnt = 0;
				printf("vol= %ld mv \r\n",runingInf.voltage);
				printf("I = %d mA \r\n",runingInf.electricity);
				printf("power = %ld mW \r\n",runingInf.power);
				printf("power_energy = %ld W.h \r\n",runingInf.power_energy);
			}
			

		}
	}
}

//========================================================================

#define SAMPLE_RESISTANCE_MR	1//使用的采样锰铜电阻mR值

#define UART_IND_HD			0
#define UART_IND_5A			1
#define UART_IND_VK			2
#define UART_IND_VT			5
#define UART_IND_IK			8
#define UART_IND_IT			11
#define UART_IND_PK			14
#define UART_IND_PT			17
#define UART_IND_FG			20
#define UART_IND_EN			21
#define UART_IND_SM			23

#define USER_ARRAY_LEN   	3//平滑滤波buf长度
#define COUNT_NUM   	1//超时更新数据次数

//8032电能计数脉冲溢出时的数据
#define ENERGY_FLOW_NUM			65536   //电量采集，电能溢出时的脉冲计数值

RuningInf_t runingInf = {0};
static bool power_flag = true;

//获取电压、电流、功率的有限数据（返回一个此数组中的，除了最大最小值中的第一个值）
unsigned long getVIPvalue(unsigned long *arr)
{
	int maxIndex = 0;
	int minIndex = 0;
//	unsigned long sum = 0;
	int j = 0;

	for(j = 1; j<USER_ARRAY_LEN; j++){
		if(arr[maxIndex] <= arr[j]){//避免所有数据一样时minIndex等于maxIndex
			maxIndex = j;
		}
		if(arr[minIndex] > arr[j]){
			minIndex = j;
		}
	}
	
	for(j = 0; j<USER_ARRAY_LEN; j++){
		if((maxIndex == j)||(minIndex == j)){
			continue;
		}
		else{
			return arr[j];
		}
	}
	return 0;
}

//检测电压电流功率是否需要更新（检测dat与arr中的第一个是否相同）
int isUpdataNewData(unsigned long *arr,unsigned long dat)
{
	if(arr[0] == dat){
		return 0;
	}
	else{
		return 1;
	}
}

//更新电压、电流、功率的列表(将dat塞到arr中的第一位)
void updataVIPvalue(unsigned long *arr,unsigned long dat)
{
	int ii = USER_ARRAY_LEN-1;
	for(ii = USER_ARRAY_LEN-1; ii > 0; ii--){
		arr[ii] = arr[ii-1];
	}
	arr[0] = dat;
}

//更新所有电压、电流、功率的列表(将arr中的所有的值设置为dat)
void resetVIPvalue(unsigned long *arr,unsigned long dat)//更新所有电压、电流、功率的列表
{	
	int ii = USER_ARRAY_LEN-1;
	for(ii = USER_ARRAY_LEN-1; ii >= 0; ii--){
		arr[ii] = dat;
	}
}

int DealUartInf(unsigned char *inDataBuffer,int recvlen)
{
	unsigned char     startFlag     = 0;
	
	unsigned long	  voltage_k	    = 0;
	unsigned long	  voltage_t     = 0;
	unsigned long	  voltage       = 0;
	static unsigned long voltage_a[USER_ARRAY_LEN]  = {0};
	static unsigned int  voltageCnt	= 0;

	unsigned long	  electricity_k = 0;
	unsigned long	  electricity_t = 0;
	unsigned long	  electricity   = 0;
	static unsigned long electricity_a[USER_ARRAY_LEN]  = {0};
	static unsigned int  electricityCnt	= 0;

	unsigned long	  power_k = 0;
	unsigned long	  power_t = 0;
	unsigned long	  power	  = 0;
	static unsigned long power_a[USER_ARRAY_LEN]= {0};
	static unsigned int  powerCnt	= 0;
	static unsigned long powerNewFlag = 1;
	
	unsigned int	  energy_cnt     = 0;
	unsigned char	  energyFlowFlag = 0;

	startFlag = inDataBuffer[UART_IND_HD];
	switch(startFlag)
	{
		case 0x55:
		{
			if((inDataBuffer[UART_IND_FG]&0x40) == 0x40){//获取当前电压标致，为1时说明电压检测OK
				voltage_k = ((inDataBuffer[UART_IND_VK] << 16)|(inDataBuffer[UART_IND_VK+1] << 8)|(inDataBuffer[UART_IND_VK+2]));//电压系数
				voltage_t = ((inDataBuffer[UART_IND_VT] << 16)|(inDataBuffer[UART_IND_VT+1] << 8)|(inDataBuffer[UART_IND_VT+2]));//电压周期
				
				if(isUpdataNewData(voltage_a,voltage_t)){
					updataVIPvalue(voltage_a,voltage_t);
					voltageCnt = 0;
				}
				else{
					voltageCnt++;
					if(voltageCnt >= COUNT_NUM){
						voltageCnt = 0;
						updataVIPvalue(voltage_a,voltage_t);
					}
				}
				//printf("voltage:%d,%d,%d\r\n",voltage_a[0],voltage_a[1],voltage_a[2]);
				voltage_t = getVIPvalue(voltage_a);
				
				if(voltage_t == 0){
					voltage = 0;
				}
				else{
					voltage = voltage_k * 100 / voltage_t;//电压10mV值，避免溢出
					voltage = voltage * 10;//电压mV值

					runingInf.voltage = voltage*D_VOLTAGE;//计算最终电压                   
				}

				//printf("Vk = %d,Vt = %d,v = %d\r\n",voltage_k,voltage_t,voltage);
				
				// printf("!!!!!!!!!!!!!!!!!!!!!!!vol= %ld mv\r\n",runingInf.voltage);
				
			}
			else{
				// printf("%s(%d):V Flag Error\r\n",__func__,__LINE__);
			}
			
			if((inDataBuffer[UART_IND_FG]&0x20) == 0x20){//获取当前电流标致，为1时说明电流检测OK
				electricity_k = ((inDataBuffer[UART_IND_IK] << 16)|(inDataBuffer[UART_IND_IK+1] << 8)|(inDataBuffer[UART_IND_IK+2]));//电流系数
				electricity_t = ((inDataBuffer[UART_IND_IT] << 16)|(inDataBuffer[UART_IND_IT+1] << 8)|(inDataBuffer[UART_IND_IT+2]));//电流周期

				if(isUpdataNewData(electricity_a,electricity_t)){
					updataVIPvalue(electricity_a,electricity_t);
					electricityCnt = 0;
				}
				else{
					electricityCnt++;
					if(electricityCnt >= COUNT_NUM){
						electricityCnt = 0;
						updataVIPvalue(electricity_a,electricity_t);
					}
				}
				//printf("electricity:%d,%d,%d\r\n",electricity_a[0],electricity_a[1],electricity_a[2]);
				electricity_t = getVIPvalue(electricity_a);
				
				if(electricity_t == 0){
					electricity = 0;
				}
				else{
					electricity = electricity_k * 100 / electricity_t;//电流10mA值，避免溢出
					electricity = electricity * 10;//电流mA值
					#if(SAMPLE_RESISTANCE_MR == 1)
					//由于使用1mR的电阻，电流和功率需要不除以2
					#elif(SAMPLE_RESISTANCE_MR == 2)
					//由于使用2mR的电阻，电流和功率需要除以2
					electricity >>= 1;
					#endif

					runingInf.electricity = electricity*D_CURRENT;//计算最终电流             
				}
				//printf("Ik = %d,It = %d,I = %d\r\n",electricity_k,electricity_t,electricity);
				
				// printf("!!!!!!!!!electricity = %d mA\r\n",runingInf.electricity);
			}
			else{
				// printf("%s(%d):I Flag Error\r\n",__func__,__LINE__);
			}

			if((inDataBuffer[UART_IND_FG]&0x10) == 0x10){//获取当前功率标致，为1时说明功率检测OK
				powerNewFlag = 0;
				power_k = ((inDataBuffer[UART_IND_PK] << 16)|(inDataBuffer[UART_IND_PK+1] << 8)|(inDataBuffer[UART_IND_PK+2]));//功率系数
				power_t = ((inDataBuffer[UART_IND_PT] << 16)|(inDataBuffer[UART_IND_PT+1] << 8)|(inDataBuffer[UART_IND_PT+2]));//功率周期
				
				if(isUpdataNewData(power_a,power_t)){
					updataVIPvalue(power_a,power_t);
					powerCnt = 0;
				}
				else{
					powerCnt++;
					if(powerCnt >= COUNT_NUM){
						powerCnt = 0;
						updataVIPvalue(power_a,power_t);
					}
				}
				//printf("power:%d,%d,%d\r\n",power_a[0],power_a[1],power_a[2]);
				power_t = getVIPvalue(power_a);
				
				if(power_t == 0){
					power = 0;
				}
				else{
					power = power_k * 100 / power_t;//功率10mw值，避免溢出
					power = power * 10;//功率mw值
					#if(SAMPLE_RESISTANCE_MR == 1)
					//由于使用1mR的电阻，电流和功率需要不除以2
					#elif(SAMPLE_RESISTANCE_MR == 2)
					//由于使用2mR的电阻，电流和功率需要除以2
					power >>= 1;
					#endif

					//runingInf.power = power*D_CURRENT*D_VOLTAGE;//计算最终功率
					//2023-07-07修改，
					runingInf.power = power*D_POWER;//计算最终功率
					
				}
			//	printf("Pk = %d,Pt = %d,P = %d\r\n",power_k,power_t,power);
				// printf("!!!!!!!!power = %d mW\r\n",runingInf.power);
				
			}
			else if(powerNewFlag == 0){
				power_k = ((inDataBuffer[UART_IND_PK] << 16)|(inDataBuffer[UART_IND_PK+1] << 8)|(inDataBuffer[UART_IND_PK+2]));//功率系数
				power_t = ((inDataBuffer[UART_IND_PT] << 16)|(inDataBuffer[UART_IND_PT+1] << 8)|(inDataBuffer[UART_IND_PT+2]));//功率周期
				// printf("!!!!!!!!!!!!!!!!!!!!!!!!Pk = %d, %d, %d\r\n",inDataBuffer[UART_IND_PK],inDataBuffer[UART_IND_PK+1],inDataBuffer[UART_IND_PK+2]);
				if(isUpdataNewData(power_a,power_t)){
					unsigned long powerData = getVIPvalue(power_a);
					if(power_t > powerData){
						if((power_t - powerData) > (powerData >> 2)){
							resetVIPvalue(power_a,power_t);
						}
					}
				}
				//printf("power:%d,%d,%d\r\n",power_a[0],power_a[1],power_a[2]);
				power_t = getVIPvalue(power_a);
				
				if(power_t == 0){
					power = 0;
				}
				else{
					power = power_k * 100 / power_t;//功率10mw值，避免溢出
					power = power * 10;//功率mw值
					#if(SAMPLE_RESISTANCE_MR == 1)
					//由于使用1mR的电阻，电流和功率需要不除以2
					#elif(SAMPLE_RESISTANCE_MR == 2)
					//由于使用2mR的电阻，电流和功率需要除以2
					power >>= 1;
					#endif
					
					//runingInf.power = power*D_CURRENT*D_VOLTAGE;//计算最终功率
					//2023-07-07修改，
					runingInf.power = power*D_POWER;//计算最终功率
				}
				//printf("Pk = %d,Pt = %d,P = %d\r\n",power_k,power_t,power);
				
				//printf("power = %d mW\r\n",runingInf.power);
			}
			
			energyFlowFlag = (inDataBuffer[UART_IND_FG] >> 7);//获取当前电能计数溢出标致
			runingInf.energyCurrent = ((inDataBuffer[UART_IND_EN] << 8)|(inDataBuffer[UART_IND_EN+1]));//更新当前的脉冲计数值
            if(power_flag){//避免7231n重启，但是计量芯片没有重启，导致数据错误。
                power_flag = false;//第一次启动电量计芯片，更新energyLast数据
                runingInf.energyLast = runingInf.energyCurrent;
            }
			if(runingInf.energyFlowFlag != energyFlowFlag){//每次计数溢出时更新当前脉冲计数值
				runingInf.energyFlowFlag = energyFlowFlag;
				if(runingInf.energyCurrent > runingInf.energyLast){
					runingInf.energyCurrent = 0;
				}
				energy_cnt = runingInf.energyCurrent + ENERGY_FLOW_NUM - runingInf.energyLast;
			}
			else{
                if(runingInf.energyCurrent > runingInf.energyLast){
				    energy_cnt = runingInf.energyCurrent - runingInf.energyLast;
                }
			}

			
			runingInf.energyLast = runingInf.energyCurrent;
			runingInf.energy += (energy_cnt * 10);//电能个数累加时扩大10倍，计算电能是除数扩大10倍，保证计算精度
            
            // printf("!!!!!!!!!!!!!!!!!!!!energy = %d W.h\r\n",runingInf.energy);
            
			runingInf.energyUnit = 0xD693A400 >> 1;
            // printf("!!!!!!!!!!!!!!!!!!!!1runingInf.energyUnit = (%ld) \r\n",runingInf.energyUnit);
            //   printf("!!!!!!!!!!!!!!!!!!!!111runingInf.energyUnit = (%ld) \r\n",(power_k >> 1));
			if(power_k >> 1)
				runingInf.energyUnit /= (power_k >> 1);//1mR采样电阻0.001度电对应的脉冲个数
            //  printf("!!!!!!!!!!!!!!!!!!!!2runingInf.energyUnit = (%ld) \r\n",runingInf.energyUnit);
			#if(SAMPLE_RESISTANCE_MR == 1)
			//1mR锰铜电阻对应的脉冲个数
			#elif(SAMPLE_RESISTANCE_MR == 2)
			//2mR锰铜电阻对应的脉冲个数
			runingInf.energyUnit = (runingInf.energyUnit << 1);//2mR采样电阻0.001度电对应的脉冲个数
			#endif
			runingInf.energyUnit =runingInf.energyUnit * 10;//0.001度电对应的脉冲个数(计算个数时放大了10倍，所以在这里也要放大10倍)
// printf("!!!!!!!!!!!!!!!!!!!!3runingInf.energyUnit = (%ld) \r\n",runingInf.energyUnit);

            //runingInf.energyUnit = runingInf.energyUnit/188*100;
            //runingInf.energyUnit = runingInf.energyUnit/(D_CURRENT*D_VOLTAGE);
            //2023-07-07修改，
						runingInf.energyUnit = runingInf.energyUnit/(D_POWER);
			
			//电能使用量=runingInf.energy/runingInf.energyUnit;//单位是0.001度
			
			runingInf.power_energy = runingInf.energy/runingInf.energyUnit;

// printf("!!!!!!!!!!!!!!!!!!!!power_k = (%ld) \r\n",power_k);
// printf("!!!!!!!!!!!!!!!!!!!!runingInf.energyUnit = (%ld) \r\n",runingInf.energyUnit);
// printf("!!!!!!!!!!!!!!!!!!!!runingInf.energy = (%ld) \r\n",runingInf.energy);
// printf("!!!!!!!!!!!!!!!!!!!!D_CURRENT*D_VOLTAGE = (%f) \r\n",(D_CURRENT*D_VOLTAGE));
// printf("!!!!!!!!!!!!!!!!!!!!power_energy = %ld W.h\r\n",runingInf.power_energy);
			// printf("!!!!!!!!!!!!!!!!!!!!power_energy = %d W.h\r\n",runingInf.power_energy);
            //power_energy_proc();//过流过压检测
			break;
		}
		case 0xAA://芯片未校准
		{			
			// printf("HLW8032 not check\r\n");
			break;
		}
		default :
		{
			if((startFlag & 0xF1) == 0xF1){//存储区异常，芯片坏了
				//芯片坏掉，反馈服务器
				// printf("HLW8032 broken\r\n");
			}

			if((startFlag & 0xF2) == 0xF2){//功率异常
				runingInf.power = 0;//获取到的功率是以0.1W为单位
				power = 0;
				//printf("Power Error\r\n");
			}
			else{
				if((inDataBuffer[UART_IND_FG]&0x10) == 0x10){
					powerNewFlag = 0;
					power_k = ((inDataBuffer[UART_IND_PK] << 16)|(inDataBuffer[UART_IND_PK+1] << 8)|(inDataBuffer[UART_IND_PK+2]));//功率系数
					power_t = ((inDataBuffer[UART_IND_PT] << 16)|(inDataBuffer[UART_IND_PT+1] << 8)|(inDataBuffer[UART_IND_PT+2]));//功率周期
					
					if(isUpdataNewData(power_a,power_t)){
						updataVIPvalue(power_a,power_t);
						powerCnt = 0;
					}
					else{
						powerCnt++;
						if(powerCnt >= COUNT_NUM){
							powerCnt = 0;
							updataVIPvalue(power_a,power_t);
						}
					}
					//printf("power:%d,%d,%d\r\n",power_a[0],power_a[1],power_a[2]);
					power_t = getVIPvalue(power_a);
					
					if(power_t == 0){
						power = 0;
					}
					else{
						power = power_k * 100 / power_t;//功率10mw值，避免溢出
						power = power * 10;//功率mw值
						#if(SAMPLE_RESISTANCE_MR == 1)
						//由于使用1mR的电阻，电流和功率需要不除以2
						#elif(SAMPLE_RESISTANCE_MR == 2)
						//由于使用2mR的电阻，电流和功率需要除以2
						power >>= 1;
						#endif
						//runingInf.power = power*1*D_VOLTAGE;//计算最终功率
						//2023-07-07修改-hiliwi
						//runingInf.power = power*D_CURRENT*D_VOLTAGE;//计算最终功率
						//2023-07-07修改，
						runingInf.power = power*D_POWER;//计算最终功率
					}
					//printf("Pk = %d,Pt = %d,P = %d\r\n",power_k,power_t,power);

					//printf("E_power = %d mW\r\n",runingInf.power);
				}
				else if(powerNewFlag == 0){
					power_k = ((inDataBuffer[UART_IND_PK] << 16)|(inDataBuffer[UART_IND_PK+1] << 8)|(inDataBuffer[UART_IND_PK+2]));//功率系数
					power_t = ((inDataBuffer[UART_IND_PT] << 16)|(inDataBuffer[UART_IND_PT+1] << 8)|(inDataBuffer[UART_IND_PT+2]));//功率周期
					
					if(isUpdataNewData(power_a,power_t)){
						unsigned long powerData = getVIPvalue(power_a);
						if(power_t > powerData){
							if((power_t - powerData) > (powerData >> 2)){
								resetVIPvalue(power_a,power_t);
							}
						}
					}
					//printf("power:%d,%d,%d\r\n",power_a[0],power_a[1],power_a[2]);
					power_t = getVIPvalue(power_a);
					
					if(power_t == 0){
						power = 0;
					}
					else{
						power = power_k * 100 / power_t;//功率10mw值，避免溢出
						power = power * 10;//功率mw值
						#if(SAMPLE_RESISTANCE_MR == 1)
						//由于使用1mR的电阻，电流和功率需要不除以2
						#elif(SAMPLE_RESISTANCE_MR == 2)
						//由于使用2mR的电阻，电流和功率需要除以2
						power >>= 1;
						#endif
						//runingInf.power = power*1*D_VOLTAGE;//计算最终功率
						//2023-07-07修改,hiliwi
						//runingInf.power = power*D_CURRENT*D_VOLTAGE;//计算最终功率
						//2023-07-07修改，
						runingInf.power = power*D_POWER;//计算最终功率
					}
					//printf("Pk = %d,Pt = %d,P = %d\r\n",power_k,power_t,power);
					//printf("E1_power = %d mW\r\n",runingInf.power);
				}
			}

			if((startFlag & 0xF4) == 0xF4){//电流异常
				runingInf.electricity = 0;//获取到的电流以0.01A为单位				
				electricity = 0;
			}
			else{
				if((inDataBuffer[UART_IND_FG]&0x20) == 0x20){
					electricity_k = ((inDataBuffer[UART_IND_IK] << 16)|(inDataBuffer[UART_IND_IK+1] << 8)|(inDataBuffer[UART_IND_IK+2]));//电流系数
					electricity_t = ((inDataBuffer[UART_IND_IT] << 16)|(inDataBuffer[UART_IND_IT+1] << 8)|(inDataBuffer[UART_IND_IT+2]));//电流周期

					if(isUpdataNewData(electricity_a,electricity_t)){
						updataVIPvalue(electricity_a,electricity_t);
						electricityCnt = 0;
					}
					else{
						electricityCnt++;
						if(electricityCnt >= COUNT_NUM){
							electricityCnt = 0;
							updataVIPvalue(electricity_a,electricity_t);
						}
					}
					//printf("electricity:%d,%d,%d\r\n",electricity_a[0],electricity_a[1],electricity_a[2]);
					electricity_t = getVIPvalue(electricity_a);
					
					if(electricity_t == 0){
						electricity = 0;
					}
					else{
						electricity = electricity_k * 100 / electricity_t;//电流10mA值，避免溢出
						electricity = electricity * 10;//电流mA值
						#if(SAMPLE_RESISTANCE_MR == 1)
						//由于使用1mR的电阻，电流和功率需要不除以2
						#elif(SAMPLE_RESISTANCE_MR == 2)
						//由于使用2mR的电阻，电流和功率需要除以2
						electricity >>= 1;
						#endif
						
						runingInf.electricity = electricity*1;//计算最终电流             
					}
					//printf("Ik = %d,It = %d,I = %d\r\n",electricity_k,electricity_t,electricity);

					//printf("E_electricity = %d mA\r\n",runingInf.electricity);
				}
				else{
					//printf("%s(%d):I Flag Error\r\n",__func__,__LINE__);
				}
			}
			
			if((startFlag & 0xF8) == 0xF8){//电压异常
				runingInf.voltage = 0;//获取到的电压是以0.1V为单位				
				voltage = 0;
			}
			else{
				if((inDataBuffer[UART_IND_FG]&0x40) == 0x40){//获取当前电压标致，为1时说明电压检测OK
					voltage_k = ((inDataBuffer[UART_IND_VK] << 16)|(inDataBuffer[UART_IND_VK+1] << 8)|(inDataBuffer[UART_IND_VK+2]));//电压系数
					voltage_t = ((inDataBuffer[UART_IND_VT] << 16)|(inDataBuffer[UART_IND_VT+1] << 8)|(inDataBuffer[UART_IND_VT+2]));//电压周期
					
					if(isUpdataNewData(voltage_a,voltage_t)){
						updataVIPvalue(voltage_a,voltage_t);
						voltageCnt = 0;
					}
					else{
						voltageCnt++;
						if(voltageCnt >= COUNT_NUM){
							voltageCnt = 0;
							updataVIPvalue(voltage_a,voltage_t);
						}
					}
					//printf("voltage:%d,%d,%d\r\n",voltage_a[0],voltage_a[1],voltage_a[2]);
					voltage_t = getVIPvalue(voltage_a);
					
					if(voltage_t == 0){
						voltage = 0;
					}
					else{
						voltage = voltage_k * 100 / voltage_t;//电压10mV值，避免溢出
						voltage = voltage * 10;//电压mV值
						runingInf.voltage = voltage*D_VOLTAGE;//计算最终电压      
					}
					//printf("Vk = %d,Vt = %d,v = %d\r\n",voltage_k,voltage_t,voltage);
					//printf("E_vol= %d mv\r\n",runingInf.voltage);
				}
				else{
					//printf("%s(%d):V Flag Error\r\n",__func__,__LINE__);
				} 
			}
			//printf("0x%x:V = %d;I = %d;P = %d;\r\n",startFlag,voltage,electricity,power);
			break;
		}
	}
	return 1;
}


//电量上报
static uint32_t old_voltage_value = 0;
static uint32_t old_electricity_value = 0;
static uint32_t old_power_value = 0;
void updata_power_energy_and_clear(void)
{
    //消除误差
    if(runingInf.energy > (runingInf.power_energy*runingInf.energyUnit)){
        runingInf.energy = runingInf.energy - runingInf.power_energy*runingInf.energyUnit;
    }
    else{
        runingInf.energy = 0;
    }

	//读取之前保存的power_energy_sum
    // runingInf.power_energy_sum = orb_state_handle("get_power_con",0);
    runingInf.power_energy_sum += runingInf.power_energy;

    runingInf.power_energy = 0;


    old_electricity_value = runingInf.electricity ;
    old_voltage_value = runingInf.voltage ;
    old_power_value = runingInf.power;
    
	//上传当前的power_energy_sum
    // orb_state_handle("set_power_con",runingInf.power_energy_sum);
}

void power_energy_report_judge(void)
{

    if((runingInf.power_energy >= 10)//dif 0.01Kw.h
	||(labs((long)(runingInf.voltage - old_voltage_value)) >= 5000) // diff 5v
	||(labs((long)(runingInf.electricity - old_electricity_value)) >= 50) // diff 0.05A
	||(labs((long)(runingInf.power - old_power_value)) >= 5000) // diff 5W
    // ||((abs(runingInf.voltage - old_voltage_value)) >= 5000)//diff 5v
    // ||((abs(runingInf.electricity - old_electricity_value)) >= 50)//diff 0.05A
    // ||((abs(runingInf.power - old_power_value)) >= 5000)//diff 5W
    ){
        updata_power_energy_and_clear();

		//执行更新电能数据并清除旧数据任务后，
        // if(QueryTask_TmrQueue(powerConTimingReport)){
        //     DelTask_TmrQueue(powerConTimingReport);
        //     AddTask_TmrQueue(POWER_CON_TIMING, POWER_CON_TIMING, powerConTimingReport);
        // }
    }
}

//过流过压检测
void power_energy_proc(void)
{
    static uint8_t over_voltage_scan_num = 0;
    static uint8_t over_electricity_scan_num = 0;
    bool protect_falg = false;

    power_energy_report_judge();

    //过压检测
    if(runingInf.voltage > (22*12*1000))  //220v*1.2
    {
        if((++over_voltage_scan_num) > 3){
            over_voltage_scan_num = 0;
			//过压事件开启
            //over_voltage_protect_report(true);
            protect_falg = true;
        }
    }
    else{
        over_voltage_scan_num = 0;
		//过压事件解除
        //over_voltage_protect_report(false);
    } 

    //过流检测
    if(runingInf.electricity > (12*1000))  //10A*1.2
    {
        if((++over_electricity_scan_num) > 3){
            over_electricity_scan_num = 0;
			//过流事件开启
            //over_current_protect_report(true);
            protect_falg = true;
        }
    }
    else{
        over_electricity_scan_num = 0;
		//过流事件解除
        //over_current_protect_report(false);
    } 

	//当过流或过压时，如过继电器还闭合则断开继电器
    if(protect_falg /*&& 检测继电器状态*/){ 
        //断开继电器
    }
}

//此任务定时更新电能数据并清除旧数据默认1H
void powerConTimingReport(void)
{
    updata_power_energy_and_clear();

}

void power_energy_print(void)
{
    printf("\r\n");
    printf("######\r\n");
    printf("I = %d mA \r\n",runingInf.electricity);
    printf("vol= %ld mv \r\n",runingInf.voltage);
    printf("power = %ld mW \r\n",runingInf.power);
    printf("powerenergy_energy = %ld W.h \r\n",runingInf.power_energy);
    printf("power_energy_sum = %ld W.h \r\n",runingInf.power_energy_sum);
    printf("######\r\n");
    printf("energy = %ld W.h \r\n",runingInf.energy);
    printf("energyUnit = %ld W.h \r\n",runingInf.energyUnit);
    printf("energyCurrent = %d W.h \r\n",runingInf.energyCurrent);
    printf("energyLast = %d W.h \r\n",runingInf.energyLast);
    printf("energyFlowFlag = %d W.h \r\n",runingInf.energyFlowFlag);
    printf("\r\n");
}




